// 不能直接导入uts import { getDeviceId16 } from "./app-android/index.uts"
import { getDeviceId16, saveID, getID } from "@/uni_modules/droid-util"

class OaidUtil {

  _getDeviceId() {
    const deviceInfoResult = uni.getDeviceInfo()
    // console.log("getDeviceId >>> ", deviceInfoResult);
    return deviceInfoResult.deviceId
  }

  _resolveDeviceId(resolve, reject) {
    console.log();
    // 使用deviceid,如果获取不到则使用uts 获取生成id
    const deviceId = this._getDeviceId() || getDeviceId16()
    deviceId && saveID("_oaid_", deviceId?.toLowerCase())
    resolve({ flag: deviceId ? true : false, e: deviceId?.toLowerCase() })
    return false
  }

  getOAID() {
    const that = this
    return new Promise((resolve, reject) => {
      // #ifdef APP-PLUS
      try {
        debugger
        // 先缓存中获取
        const oaid = getID("_oaid_")
        if (oaid) {
          console.log(`cache OAID=${oaid}`);
          return resolve({ flag: true, e: oaid })
        }

        //检查系统版本再获取OAID
        uni.getSystemInfo({
          success(res) {
            // Android 系统大于10
            if (parseInt(res.system.split('.')[0]) >= 10) {
              // Android - 10+ (支持) : 仅在华为、OPPO、VIVO、小米、联想等设备支持
              plus.device.getOAID({
                success: function(e) {
                  console.log('getOAID success: ' + JSON.stringify(e));
                  saveID("_oaid_", e.oaid)
                  resolve({ flag: true, e: e.oaid })
                },
                fail: function(e) {
                  console.log('getOAID failed: ' + JSON.stringify(e));
                  // oaid 获取失败使 deviceID 
                  // imei imsi uuid
                  plus.device.getInfo({
                    success: (info) => {
                      const uuid = info?.uuid || info?.imei || info?.imsi
                      if (!uuid) {
                        that._resolveDeviceId(resolve, reject)
                        return;
                      }
                      saveID("_oaid_", uuid)
                      resolve({ flag: true, e: uuid })
                    },
                    fail: () => {
                      that._resolveDeviceId(resolve, reject)
                    }
                  });
                }
              })
            } else {
              // 低版本使用uuid
              const uuid = plus.device.uuid
              console.log(`OaidUtil 低版本使用uuid ${uuid}`);
              if (uuid) {
                saveID("_oaid_", uuid)
                resolve({ flag: true, e: uuid })
              } else {
                that._resolveDeviceId(resolve)
              }
            }
          }
        });
      } catch (error) {
        console.log("oaid util error", error)
        that._resolveDeviceId(resolve, reject)
      }
      // #endif
      
      // #ifndef APP-PLUS
      return resolve({ flag: false })
      // #endif
    })
  }

}

const oaidUtil = new OaidUtil()

export default oaidUtil